package aiingames.simulation.agent;

import java.util.List;
import java.util.Random;


import aiingames.simulation.server.Server;

import com.vividsolutions.jts.geom.Coordinate;


public class SimpleAgent extends Agent {

	Random rand = new Random();
	
	double driveX = (rand.nextDouble() - .5);
	double driveY= (rand.nextDouble() - .5);


	public SimpleAgent(int id) {
		super(id);
	}

	@Override
	public AgentAction perform(Server serv) {
		
		Coordinate location = serv.getAgentLocation(this);
		List<Coordinate> objects = serv.getNeighboringObjects(location);
		
		Coordinate n = getNearestObject(objects,location);
		double distance = n.distance(location);
		if (distance < .5) {
			this.driveX = (rand.nextDouble() - .5);
			this.driveY = (rand.nextDouble() - .5);			
		}
		
		

		Coordinate c = new Coordinate(this.driveX,this.driveY);
		double v = 1- (rand.nextDouble()/5);

		AgentAction a = new AgentAction(c,v);

		return a;

	}

	private Coordinate getNearestObject(List<Coordinate> objects, Coordinate location) {
		double minDist = Double.POSITIVE_INFINITY;
		Coordinate nearest = null;
		for (Coordinate c : objects) {
			double dist = c.distance(location);
			if (dist < minDist) {
				minDist = dist;
				nearest = c;
			}
		}
		return nearest;
	}

}
